<?php

class Application_Model_Packages implements Iterator {
    
    private $position;
    private $packagesPath;
    private $assetsPath;
    private $packagesDB = array();
    private $doctrineContainer;
    
    public function __construct($packagesPath, $assetsPath) {
        $this->position = 0;
        $this->packagesPath = $packagesPath;
        $this->assetsPath = $assetsPath;
        $this->import();
    }
    
    private function import() {
        $em = $this->getEntityManager();
        $command = "ls -1 $this->packagesPath | grep tar.gz";
        $lines = array();
        exec($command, $lines);
        foreach($lines as $package) {
            $packagePath = $this->packagesPath . "/" . $package;
            ob_start();
            system("tar xf $packagePath agent-manifest.xml --to-stdout");
            $manifest = ob_get_contents();
            ob_end_clean();
            if($this->isContentValid($manifest)) {
                $packg = new Application_Model_Package($manifest, $this->packagesPath, $package, $this->assetsPath);
                $agent = $em->getRepository('Jhub1db\Entity\Jhub1agent')->findBy(array('uaid' => $packg->agent->id));
                if(count($agent)) {
                    $packg->setInstalled($agent[0]->getInstalled());
                    $packg->setInstalledVersion($agent[0]->getVersion());
                }
                array_push($this->packagesDB, $packg);
                $packg->convertToArray();
            }
        }
    }
    
    private function isContentValid($content) {
        return 1;
    }
    
    private function getEntityManager() {
        $this->doctrineContainer = Zend_Registry::get('doctrine');
        return $this->doctrineContainer->getEntityManager();      
    }
    
    function rewind() {
        $this->position = 0;
    }

    function current() {
        if($this->packagesDB[$this->position]->isValid()) {
            return $this->packagesDB[$this->position];
        } else {
            return 0;
        }
            
    }

    function key() {
        return $this->position;
    }

    function next() {
        ++$this->position;
    }

    function valid() {
        return isset($this->packagesDB[$this->position]);
    }
    
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
?>
